package com.vinjogames.gfx;

import javax.microedition.khronos.opengles.GL10;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLUtils;

import com.vinjogames.TankGame.R;
import com.vinjogames.util.GameConVars;

public class AnimationSheet {
	private static Bitmap mAnimationSheet;
	private Context mContext;
	
	private int[][] allTextures = new int[GameConVars.GRAPHIC_MAX_TEXTURES][];//TODO:  create graphic max anims
	
	private AnimationSheet(){};

	private static class AnimationSheetHolder {
		public static final AnimationSheet instance = new AnimationSheet();
	}
	
	public static AnimationSheet getInstance(){
		return AnimationSheetHolder.instance;
	}
	
	public void setContext(Context context){ mContext = context; }
	
	public int[] getTexture(int key){
		return allTextures[key];
	}
	
	public void loadAllTextures(GL10 gl){
		if(mAnimationSheet == null){
			mAnimationSheet = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.lanimsheet);
		}
		
		allTextures[GameConVars.ANIM_EXPLOSION1] = loadTexture(gl, Bitmap.createBitmap(mAnimationSheet, 0, 0, 768,64), 64, 64);
		allTextures[GameConVars.ANIM_EXPLOSION2] = loadTexture(gl, Bitmap.createBitmap(mAnimationSheet, 0, 128, 704,64), 64, 64);
		allTextures[GameConVars.ANIM_EXPLOSION3] = loadTexture(gl, Bitmap.createBitmap(mAnimationSheet, 320, 64, 320,64), 64, 64);
		allTextures[GameConVars.ANIM_EXPLOSION4] = loadTexture(gl, Bitmap.createBitmap(mAnimationSheet, 320, 192, 320,64), 64, 64);
		allTextures[GameConVars.ANIM_FLAME] = loadTexture(gl, Bitmap.createBitmap(mAnimationSheet, 0, 64, 320,64), 64, 64);
		allTextures[GameConVars.ANIM_SPARK1] = loadTexture(gl, Bitmap.createBitmap(mAnimationSheet, 0, 192, 320,64), 64, 64);
		allTextures[GameConVars.ANIM_SPARK2] = loadTexture(gl, Bitmap.createBitmap(mAnimationSheet, 0, 256, 256,128), 64, 128);
		
		mAnimationSheet.recycle();
		mAnimationSheet = null;
	}
	
	private int[] loadTexture(GL10 gl, Bitmap bitmap, int frameWidth, int frameHeight){
		int frames = bitmap.getWidth() / frameWidth;
		int[] textures = new int[frames];
		// Generate Texture Pointer
		gl.glGenTextures(frames, textures, 0);
		for(int i = 0; i < frames; i++){
			Bitmap currentFrame = frames == 1 ? bitmap : Bitmap.createBitmap(bitmap, i*frameWidth, 0, frameWidth, frameHeight);
			// Bind to Array
			gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[i]);
			// Create Filtered Texture													NEAREST = Crisp  LINEAR = Blurred
			gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST);
			gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_NEAREST);
			// Specify Image for Bitmap
			GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, currentFrame, 0);
			currentFrame.recycle();
		}
		return textures;
	}
}
